//
//  ViewController.swift
//  QizAISwiftDemo
//
//  Created by Mephisto on 2025/4/22.
//

import QMUIKit
import QizAIFramework
import SnapKit
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.view.addSubview(self.toolView)
        self.view.addSubview(self.qizAIView)
        self.setupLayout()
        self.bindViewModel()
    }

    private func bindViewModel() {
        self.toolView.sureBtn.addTarget(
            self, action: #selector(btnClick(btn:)), for: .touchUpInside)

        self.toolView.expandSwitch.addTarget(
            self, action: #selector(expandToggle(switchV:)), for: .valueChanged)

    }

    @objc func btnClick(btn: UIButton) {
        self.view.endEditing(true)

        guard let accountNo = self.toolView.accountNoTF.text,
            !accountNo.isEmpty
        else {
            QMUITips.show(withText: "请输入AccountNo")
            return
        }

        // ❗️❗️❗️App 中 accountNo 修改后需要同步更新
        self.qizAIView.accountNo = accountNo
        QMUITips.show(withText: "AccountNo加载成功")

    }

    @objc func expandToggle(switchV: UISwitch) {
        // ❗️❗️❗qizAIView 的展开收起状态由外部控制，当状态改变后需要更新这个值
        self.qizAIView.isExpand = switchV.isOn
    }

    //MARK: - 界面布局

    private func setupLayout() {
        self.toolView.snp.makeConstraints { make in
            make.left.trailing.equalToSuperview()
            make.top.equalToSuperview().offset(60)
        }

        self.qizAIView.snp.makeConstraints { make in
            make.top.equalTo(self.toolView.snp.bottom).offset(20)
            make.leading.trailing.bottom.equalToSuperview()
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }

    //MARK: - 懒加载

    private lazy var qizAIView: QizAIView = {
//        var view = QizAIView(accountNo: "PDCxxxxx")
        var view = QizAIView()
        view.accountNo = ""
        view.delegate = self
        return view
    }()

    private lazy var toolView: ToolView = .init()

}

extension ViewController: QizAIViewDelegate {
    func qizAIView(
        _ view: QizAIFramework.QizAIView, jumpControllerWith url: URL
    ) {
        UIApplication.shared.open(url)
    }

}
